home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: division problem
- Date: 30 Jan 96 21:03:17 GMT
- Organization: Clemson University
- Message-ID: <mjs.823035797@hubcap>
- References: <31097D77.11AA@rain.org> <26JAN199622082450@erich.triumf.ca> <4eh246$u6h@airdmhor.gen.nz> <4ej4ha$66@fountain.mindlink.net> <DLzvGG.2rn@uns.bris.ac.uk> <Pine.SOL.3.90.960130150923.21923F-100000@flute>
- NNTP-Posting-Host: hubcap.clemson.edu
-
- Darrell Grainger <a378grai@cdf.toronto.edu> writes:
-
- |On Tue, 30 Jan 1996, Nathan Sidwell wrote:
-
- |> : >celcius = (fahrenheit - 32) * 5 / 9;
- |>
- |> : That's disgusting <g> as it doesn't round. Try it with 39 deg F:
- |> : (39-32)*5/9 ::= 7*5/9 ::= 35/9 ::= 3
- |> : but the actual value is 3.8... i.e. nearly 4. If you must int, 4
- |> : would be a better answer.
- |>
- |> Still no need to use floating point,
- |> celcius = ((fahrenheit - 32) * 5 + 4) / 9
-
- |This ALMOST does the trick but 4/9 = 0.44444444... and 5/9 = 0.555555....
- |What you really want to do to eliminate the rounding errors is add 0.5 to
- |the number, e.g. 1.49999... + 0.5 = 1.9999... and (int)1.9999... = 1. So
- |1.49999... rounds down to 1. Then 1.5 + 0.5 = 2.0 and (int)2.0 = 2. So
- |1.5 rounds up to 2. This is what most people consider correct rounding.
-
- For arbitrary floating-point results, this is correct, but...
-
- |In your 'trick' you would have 1.5 + 0.4444... = 1.9444... and
- |(int)1.9444... = 1. This means that 1.5 rounds down to 1. This is not
- |proper. It is close but not proper. Alternatively, adding 5/9th would round
- |up certain numbers it should not.
-
- ...in this particular example, we know that the result of the division
- will have a fractional part equal to n/9, 0 <= n <= 8. In this case,
- we see that adding 4/9 to a fractional part <= 4/9 and truncating
- rounds down, but adding 4/9 to a fractional part >= 5/9 and truncating
- rounds up. Quite clever, actually.
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-